var { request, summary, query, path, body, tags, description } = require('koa-swagger-decorator');
var _ = require('lodash');

var Project = require('../Models/Project');
var Version = require('../Models/Version');
var User = require('../Models/User');
var TestRecord = require('../Models/TestRecord');
var logTool = require('../Tools/LogTool');


const globalResponseCode = require('../base/ResponseCode');
const projectResponseCode = {
	USER_PARAMS_ERROR: { code: 30001, message: '项目成员参数错误！' },
	PROJECT_EXIST: { code: 30002, message: '项目名已存在！' },
	PROJECT_NOT_EXIST: { code: 30003, message: '项目不存在' },
	ADD_INSERT_USERS_ERROR: { code: 30004, message: '添加项目：添加项目成员失败！' },
	DELETE_FAIL: { code: 30005, message: '删除项目失败！' },
	DELETE_FAIL_EXIST_RECORD: { code: 30006, message: '项目下存在提测记录，不可删除！' },
	UPDATE_NO_AFFECT: { code: 30007, message: '修改项目成功：无任何修改' },
	UPDATE_INSERT_USERS_ERROR: { code: 30008, message: '修改项目：替换项目成员失败！' },

}

var projectSchema = {
	name: { type: 'string', required: true, example: 'mBlock' },
	description: { type: 'string', required: false, example: '' },
	users: { type: 'array', required: false, items: { type: 'object', example: { id: 5 }, description: "用户id" }, description:'项目成员'}
}

class ProjectController {

	@tags(['Project'])
	@request('post', '/project/add')
	@summary('添加项目')
	@description('项目名唯一, 只有管理员可添加')
	@body(projectSchema)
	async addProject(ctx) {
		try {
			if (ctx.session.user) {
				if (ctx.session.user.roleId !== 4) {
					return ctx.body = globalResponseCode.NO_AUTH;
				}


				let project = ctx.request.body;
				project.realname=ctx.session.user.realName;
				//console.log('##@!',project.realname)
				if (!project || !project.name) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (project.users) {
					if (!_.isArray(project.users)) {
						return ctx.body = projectResponseCode.USER_PARAMS_ERROR;
					}
					let usersParamsFilter = project.users.every((item, index, array) => {
						return item.id ? true : false;
					});
					if (!usersParamsFilter) {
						return ctx.body = projectResponseCode.USER_PARAMS_ERROR;
					}
				}
				let projectId = await Project.insert(project);
				if (projectId !== 0 && project.users && !_.isEmpty(project.users)) {
					//是否返回用户插入不成功
					let insertUserReult = await User.insertUsersToProject(projectId, project.users);
					if (!insertUserReult) {
						return ctx.body = projectResponseCode.ADD_INSERT_USERS_ERROR;
					}
				}
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, { data: { projectId: projectId } });
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			if (error.errno == 1062) {
				return ctx.body = projectResponseCode.PROJECT_EXIST;
			}
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['Project'])
	@request('delete', '/project/delete')
	@summary('删除项目')
	@description('只有管理员可删除')
	@body({
		id: { type: "int", required: true, example: 1 },
	})
	async deleteProjectById(ctx) {
		try {
			if (ctx.session.user) {
				if (ctx.session.user.roleId !== 4) {
					return ctx.body = globalResponseCode.NO_AUTH;
				}
				if (!ctx.request.body.id || !_.isInteger(ctx.request.body.id)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				let projectId = ctx.request.body.id;
				let testRecordCount = await TestRecord.queryTestRecordCountByProjectId(projectId);
				if (testRecordCount == 0) {
					let result = await Project.deleteById(projectId);
					if (result) {
						return ctx.body = globalResponseCode.SUCCESS;
					}
				} else {
					return ctx.body = projectResponseCode.DELETE_FAIL_EXIST_RECORD;
				}
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['Project'])
	@request('post', '/project/update')
	@summary('修改项目')
	@description('只有管理员可修改, 如果不修改项目成员，不要传入users参数')
	@body({
		id: { type: "int", required: true, example: 1, description: "项目id" },
		name: { type: 'string', required: false, example: 'mBlock' },
		description: { type: 'string', required: false },
		users: { type: 'array', required: false, items: { type: 'object', example: { id: 5 }, description: "用户id" }, description: "项目成员" }
	})
	async updateProject(ctx) {
		try {
			if (ctx.session.user) {
				if (ctx.session.user.roleId !== 4) {
					return ctx.body = globalResponseCode.NO_AUTH;
				}
				let project = ctx.request.body;
				if (!project.id || !_.isInteger(project.id)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (_.keys(project).length <= 1) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (project.name && !_.isString(project.name)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (project.description && !_.isString(project.description)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (project.users) {
					if (!_.isArray(project.users)) {
						return ctx.body = projectResponseCode.USER_PARAMS_ERROR;
					}
					let usersParamsFilter = project.users.every((item, index, array) => {
						return item.id ? true : false;
					});
					if (!usersParamsFilter) {
						return ctx.body = projectResponseCode.USER_PARAMS_ERROR;
					}
				}
				let nameExit = await Project.checkNameExit(project)
				let result = null
				if(nameExit){
					 result = await Project.update(project);
				}else{
					return ctx.body = projectResponseCode.PROJECT_EXIST;
				}

				if (project.users) {
					//是否返回用户插入不成功
					let insertUserReult = await User.insertUsersToProject(project.id, project.users);
					if (!insertUserReult) {
						return ctx.body = projectResponseCode.UPDATE_INSERT_USERS_ERROR;
					}
				}
				if (result) {
					return ctx.body = globalResponseCode.SUCCESS;
				} 
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			console.log(error)
			if (error.errno == 1062) {
				return ctx.body = projectResponseCode.PROJECT_EXIST;
			}
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['Project'])
	@request('post', '/project/info')
	@summary('查询项目')
	@description('根据 id 获取项目信息，包括：项目基本信息，项目成员')
	@body({
		id: { type: 'int', required: true, example: 1 }
	})
	async getProjectById(ctx) {
		try {
			if (ctx.session.user) {
				if (!ctx.request.body.id || !_.isInteger(ctx.request.body.id)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				let projectId = ctx.request.body.id;
				let project = await Project.queryById(projectId);
				if (_.isEmpty(project)) {
					return ctx.body = projectResponseCode.PROJECT_NOT_EXIST;
				}
				let users = await User.queryUsersByProjectId(projectId);
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, { data: {...project, ...users } });
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['Project'])
	@request('get', '/project/list')
	@summary('获取所有项目')
	@description('不分页，获取所有')
	async getProjectList(ctx) {
		try {
			if (ctx.session.user) {
				let projects = await Project.list();
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, { data: projects });
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['Project'])
	@request('post', '/project/versionlist')
	@summary('获取项目下的版本')
	@body({
		page: { type: 'int', required: true, example: 1 },
		size: { type: 'int', required: true, example: 10 },
		projectId: { type: 'int', require: false, example: 2, description: '项目id' },
		testStatus: { type: 'int', require: false, example: 1, description: '提测状态' }
	})
	async getVersionByProjectId(ctx) {
		try {
			if (ctx.session.user) {
				let condition = ctx.request.body;
				if (!condition || !condition.projectId  ) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				let list = await Version.getVersionByProjectId(ctx.request.body);
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, {data:list});
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['Project'])
	@request('post', '/project/queryCurrentUserOwnedProjects')
	@summary('获取当前用户所属的项目')
	@body({
		projectId: { type: 'int', require: false, example: 2, description: '项目id' },
	})

	async getCurrentUserOwnedProjects(ctx){
		try {
			if (ctx.session.user) {
				let currentProject = {};
				let versions = [];
				let projects = await User.queryProjectsByUserId(ctx.session.user.id);
				let users = [];
				if(!_.isEmpty(projects)){
					let projectId = projects[0].id;
					if(ctx.request.body.projectId){
						
						if(!_.isInteger(projectId)){
							return ctx.body = globalResponseCode.PARAMS_ERROR;
						}else{
							projectId = ctx.request.body.projectId;
						}
					}
					currentProject = await Project.queryById(projectId);
					users = await User.queryUsersByProjectId(projectId);
					versions = await Version.getVersionByProjectId({projectId});
				}
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, {data: {projects, currentProject:{...currentProject, ...users}, versions}});
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

}

module.exports = new ProjectController();